package com.plugins.pluginlib;

import static com.plugins.pluginlib.broadcast.BroadcastManager.BROAD_MESSAGE_KEY;
import static com.plugins.pluginlib.utils.IConstants.FROM_HOST_MESSAGE;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.plugins.pluginlib.broadcast.BroadMessage;
import com.plugins.pluginlib.broadcast.BroadcastManager;
import com.plugins.pluginlib.internal.IIntent;
import com.plugins.pluginlib.internal.IPluginManager;
import com.plugins.pluginlib.internal.IPluginPackage;
import com.plugins.pluginlib.utils.IConstants;
import com.plugins.pluginlib.utils.JsonUtil;

/**
 */
public abstract class IBasePluginActivity extends Activity implements IPlugin {

    private static final String TAG = "IBasePluginActivity";

    /**
     * 代理activity，可以当作Context来使用，会根据需要来决定是否指向this
     */
    protected Activity mProxyActivity;

    /**
     * 等同于mProxyActivity，可以当作Context来使用，会根据需要来决定是否指向this<br/>
     * 可以当作this来使用
     */
    protected Activity that;
    protected IPluginManager mPluginManager;
    protected IPluginPackage mPluginPackage;

    protected int mFrom = IConstants.FROM_INTERNAL;

    @Override
    public void attach(Activity proxyActivity, IPluginPackage pluginPackage) {
        Log.d(TAG, "attach: proxyActivity= " + proxyActivity);
        mProxyActivity =  proxyActivity;
        that = mProxyActivity;
        mPluginPackage = pluginPackage;
    }

    private Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mFrom = savedInstanceState.getInt(IConstants.FROM, IConstants.FROM_INTERNAL);
        }
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onCreate(savedInstanceState);
            mProxyActivity = this;
            that = mProxyActivity;
        }

        mPluginManager = IPluginManager.getInstance(that);
        if(savedInstanceState!=null) {
            String packageName = savedInstanceState.getString(IConstants.EXTRA_PACKNAME, "");
            HOST_ACTION = IConstants.HOST_PUSH_MESSAGE_SUFFIX + packageName;
            PLUGIN_ACTION = IConstants.PLUGIN_PUSH_MESSAGE_SUFFIX + packageName;
            initBroadcast();
            Log.d(TAG, "onCreate: from= "
                    + (mFrom == IConstants.FROM_INTERNAL ? "DLConstants.FROM_INTERNAL" : "FROM_EXTERNAL"));
            handler.postDelayed(() -> initData(savedInstanceState), 300);
        }
    }

    @Override
    public void setContentView(View view) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.setContentView(view);
        } else {
            mProxyActivity.setContentView(view);
        }
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.setContentView(view, params);
        } else {
            mProxyActivity.setContentView(view, params);
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.setContentView(layoutResID);
        } else {
            mProxyActivity.setContentView(layoutResID);
        }
    }

    @Override
    public void addContentView(View view, LayoutParams params) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.addContentView(view, params);
        } else {
            mProxyActivity.addContentView(view, params);
        }
    }

    @Override
    public <T extends View>T findViewById(int id) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return (T)super.findViewById(id);
        } else {
            return (T)mProxyActivity.findViewById(id);
        }
    }

    @Override
    public Intent getIntent() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getIntent();
        } else {
            return mProxyActivity.getIntent();
        }
    }

    @Override
    public ClassLoader getClassLoader() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getClassLoader();
        } else {
            return mProxyActivity.getClassLoader();
        }
    }

    @Override
    public Resources getResources() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getResources();
        } else {
            return mProxyActivity.getResources();
        }
    }

    @Override
    public String getPackageName() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getPackageName();
        } else {
            return mPluginPackage.packageName;
        }
    }

    @Override
    public LayoutInflater getLayoutInflater() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getLayoutInflater();
        } else {
            return mProxyActivity.getLayoutInflater();
        }
    }

    @Override
    public MenuInflater getMenuInflater() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getMenuInflater();
        } else {
            return mProxyActivity.getMenuInflater();
        }
    }

    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getSharedPreferences(name, mode);
        } else {
            return mProxyActivity.getSharedPreferences(name, mode);
        }
    }

    @Override
    public Context getApplicationContext() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getApplicationContext();
        } else {
            return mProxyActivity.getApplicationContext();
        }
    }

    @Override
    public WindowManager getWindowManager() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getWindowManager();
        } else {
            return mProxyActivity.getWindowManager();
        }
    }

    @Override
    public Window getWindow() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getWindow();
        } else {
            return mProxyActivity.getWindow();
        }
    }

    @Override
    public Object getSystemService(String name) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.getSystemService(name);
        } else {
            return mProxyActivity.getSystemService(name);
        }
    }

    @Override
    public void finish() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.finish();
        } else {
            mProxyActivity.finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onBackPressed();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onStart() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onStart();
        }
    }

    @Override
    public void onRestart() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onRestart();
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onRestoreInstanceState(savedInstanceState);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onSaveInstanceState(outState);
        }
    }

    public void onNewIntent(Intent intent) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onNewIntent(intent);
        }
    }

    @Override
    public void onResume() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onResume();
        }
    }

    @Override
    public void onPause() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onPause();
        }
    }

    @Override
    public void onStop() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onStop();
        }
    }

    @Override
    public void onDestroy() {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onDestroy();
        }
        destroyBroadcast();
    }

    public boolean onTouchEvent(MotionEvent event) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.onTouchEvent(event);
        }
        return false;
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.onKeyUp(keyCode, event);
        }
        return false;
    }

    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onWindowAttributesChanged(params);
        }
    }

    public void onWindowFocusChanged(boolean hasFocus) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            super.onWindowFocusChanged(hasFocus);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return super.onCreateOptionsMenu(menu);
        }
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (mFrom == IConstants.FROM_INTERNAL) {
            return onOptionsItemSelected(item);
        }
        return false;
    }

    /**
     * @param iIntent
     */
    public int startActivity(IIntent iIntent) {
        return startActivityForResult(iIntent, -1);
    }

    /**
     * @param iIntent
     */
    public int startActivityForResult(IIntent iIntent, int requestCode) {
        BroadMessage broadMessage = getFromHostMessage();
        //把从宿主传过来的参数带到每一个页面
        if(broadMessage!=null){
            iIntent.putExtra(FROM_HOST_MESSAGE,JsonUtil.beanToJson(broadMessage));
        }
        if (mFrom == IConstants.FROM_EXTERNAL) {
            if (iIntent.getPluginPackage() == null) {
                iIntent.setPluginPackage(mPluginPackage.packageName);
            }
        }
        return mPluginManager.startActivityForResult(that, iIntent, requestCode);
    }
    //    /**
//     * 直接调用that.startService
//     * that 可能有两种情况
//     * 1.指向this
//     * 2.指向DLProxyActivity
//     */
    public ComponentName startService(Intent service) {
        return that.startService(service);
    }

    @Override
    public boolean stopService(Intent name) {
        // TODO Auto-generated method stub
        return super.stopService(name);
    }

    @Override
    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
        // TODO Auto-generated method stub
        return super.bindService(service, conn, flags);
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        // TODO Auto-generated method stub
        super.unbindService(conn);
    }


    /**
     * 监听host的消息
     */
    private BroadcastManager broadcastManager;
    private String HOST_ACTION ;
    private String PLUGIN_ACTION;
    private void initData(Bundle bundle){
        String data = bundle.getString(IConstants.EXTRA_FROM_HOST_MESSAGE,null);
        if(data!=null){
            BroadMessage broadMessage;
            try {
                broadMessage = JsonUtil.jsonToBean(data,BroadMessage.class);
            }catch (Exception e){
                broadMessage = new BroadMessage();
                broadMessage.setSuccess(false);
                broadMessage.setMessage(e.getMessage());
            }
            if(broadMessage!=null){
                fromHostMessage(broadMessage);
            }
        }
    }
    private synchronized void initBroadcast(){
        if(broadcastManager==null){
            broadcastManager = BroadcastManager.getInstance(that);
            broadcastManager.register(HOST_ACTION, new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    fromHostMessage(broadcastManager.getBroadMessage(intent));
                }
            });
        }
    }
    private synchronized void destroyBroadcast(){
        if(broadcastManager!=null){
            broadcastManager.unregister(HOST_ACTION);
        }
    }

    /**
     * 向宿主发送消息
     * @param message
     */
    public void sendMessageToHost(BroadMessage message){
        initBroadcast();
        if(broadcastManager!=null){
            broadcastManager.sendBroadcast(PLUGIN_ACTION,message);
        }
    }

    /**
     * host消息回调
     * @param message
     */
    public abstract void fromHostMessage(BroadMessage message);


    /**
     * 获取从host传递过来的参数
     * @return
     */
    public BroadMessage getFromHostMessage(){
        BroadMessage broadMessage = null;
        String json = that.getIntent().getStringExtra(FROM_HOST_MESSAGE);
        if(!TextUtils.isEmpty(json)){
            broadMessage = JsonUtil.jsonToBean(json,BroadMessage.class);
        }
        return broadMessage;
    }

}
